const express = require('express');
const multer = require('multer');
const path = require('path');
const cors = require('cors')
const fs = require('fs');
const app = express();
const port = 3000;

// 配置静态文件目录
app.use(express.static('public'));

app.use(cors()) 

// 确保上传目录存在
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function(req, file, cb) {
    // 使用时间戳+原始文件名，避免文件名冲突
    cb(null, Date.now() + '-' + file.originalname);
  }
});

// 创建multer实例
const upload = multer({ 
  storage: storage,
  limits: { fileSize: 10 * 1024 * 1024 } // 限制文件大小为10MB
});

// 处理单文件上传
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: '没有选择文件' });
  }
  
  res.json({ 
    message: '文件上传成功',
    file: {
      filename: req.file.filename,
      originalname: req.file.originalname,
      size: req.file.size,
      path: req.file.path
    }
  });
});

// 处理多文件上传
app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
  if (!req.files || req.files.length === 0) {
    return res.status(400).json({ message: '没有选择文件' });
  }
  
  const fileInfos = req.files.map(file => ({
    filename: file.filename,
    originalname: file.originalname,
    size: file.size,
    path: file.path
  }));
  
  res.json({ 
    message: `成功上传了 ${req.files.length} 个文件`,
    files: fileInfos
  });
});

// 获取已上传文件列表
app.get('/files', (req, res) => {
  fs.readdir(uploadDir, (err, files) => {
    if (err) {
      return res.status(500).json({ message: '无法读取文件列表', error: err });
    }
    res.json({ files });
  });
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
}); 